import pygame
import random
import os

# 初始化Pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 720
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("羊了个羊")

# 颜色定义
BG_COLOR = (255, 255, 255)

# 卡片尺寸和间距
CARD_WIDTH = 55
CARD_HEIGHT = 70
SPACING = 10
STACK_OFFSET = 3  # 堆叠卡片的偏移量

# 游戏区域布局
GRID_ROWS = 4
GRID_COLS = 5
grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
GRID_TOP = 100

# 槽位区域设置
SLOT_ROWS = 1
SLOT_COLS = 7  # 最多存放7个卡片
slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
SLOT_HEIGHT = CARD_HEIGHT + 20

# 道具按钮设置
ITEM_BUTTON_WIDTH = CARD_WIDTH  # 使用卡片宽度
ITEM_BUTTON_HEIGHT = CARD_HEIGHT  # 使用卡片高度
ITEM_BUTTON_LEFT = 20
# 向上移动按钮位置，将值调小
ITEM_BUTTON_TOP = 50
# 加载自定义按钮图片
try:
    button_image_path = os.path.join(os.path.dirname(__file__), "image", "tile8.png")
    button_image = pygame.image.load(button_image_path)
    button_image = pygame.transform.scale(button_image, (ITEM_BUTTON_WIDTH, ITEM_BUTTON_HEIGHT))
    print("道具按钮图片加载成功")
except Exception as e:
    print(f"道具按钮图片加载失败: {e}")
    button_image = None

# 按钮可用次数
ITEM_USE_TIMES = 1
ITEM_USED = False

# 加载背景图像
try:
    image_folder = os.path.join(os.path.dirname(__file__), "image")
    background_path = os.path.join(image_folder, "back.png")
    background_img = pygame.image.load(background_path)
    background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH, SCREEN_HEIGHT))
    print("主背景图像加载成功")
except Exception as e:
    print(f"主背景图像加载失败: {e}")
    background_img = None

# 加载槽位背景图像
try:
    slot_bg_path = os.path.join(image_folder, "back2.png")
    slot_bg_img = pygame.image.load(slot_bg_path)
    slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
    print("槽位背景图像加载成功")
except Exception as e:
    print(f"槽位背景图像加载失败: {e}")
    slot_bg_img = None

# 加载卡片图片
card_images = []
try:
    for i in range(5):
        tile_path = os.path.join(image_folder, f"tile{i}.png") if i > 0 else os.path.join(image_folder, "tile.png")
        if os.path.exists(tile_path):
            img = pygame.image.load(tile_path)
            img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
            card_images.append(img)
            print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
        else:
            print(f"卡片图片 {tile_path} 不存在")

    if not card_images:
        raise Exception("没有找到任何卡片图片")

except Exception as e:
    print(f"卡片图片加载失败: {e}")
    COLORS = [
        (255, 0, 0),  # 红
        (0, 255, 0),  # 绿
        (0, 0, 255),  # 蓝
        (255, 255, 0),  # 黄
        (128, 0, 128),  # 紫
    ]

# 游戏状态
slots = []
score = 0
game_over = False
game_won = False
falling_cards = []  # 存储正在下落的卡片信息
FALLING_SPEED = 45  # 定义卡片下落速度


def check_victory():
    """检查是否胜利"""
    for row in grid:
        for stack in row:
            if len(stack) > 0:
                return False
    return len(slots) == 0


# 初始化卡片堆
grid = []
for row in range(GRID_ROWS):
    grid_row = []
    for col in range(GRID_COLS):
        layers = random.randint(3, 5)
        max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
        stack = [random.randint(0, max_card_type) for _ in range(layers)]
        stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
        grid_row.append(stack)
    grid.append(grid_row)

# 主循环
clock = pygame.time.Clock()
running = True

while running:
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
            x, y = pygame.mouse.get_pos()
            # 检查是否点击道具按钮
            if ITEM_BUTTON_LEFT <= x <= ITEM_BUTTON_LEFT + ITEM_BUTTON_WIDTH and ITEM_BUTTON_TOP <= y <= ITEM_BUTTON_TOP + ITEM_BUTTON_HEIGHT:
                if ITEM_USE_TIMES > 0 and not ITEM_USED:
                    slots.clear()
                    ITEM_USE_TIMES -= 1
                    ITEM_USED = True
            else:
                # 计算点击位置
                grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
                grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
                # 检查点击范围
                if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
                    if len(grid[grid_row][grid_col]) > 0:
                        # 检查槽位是否已满（改为7块）
                        if len(slots) >= SLOT_COLS:  # SLOT_COLS = 7
                            game_over = True
                            continue

                        # 取出顶层卡片
                        card = grid[grid_row][grid_col].pop()
                        # 记录卡片起始位置
                        start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING) + len(
                            grid[grid_row][grid_col]) * (STACK_OFFSET // 2)
                        start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) - len(
                            grid[grid_row][grid_col]) * STACK_OFFSET
                        target_x = SLOT_LEFT + len(slots) * (CARD_WIDTH + 5)
                        target_y = SLOT_TOP
                        falling_cards.append((card, start_x, start_y, target_x, target_y))
                        slots.append(card)

                        # 检查连续三个相同卡片
                        if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
                            del slots[-3:]
                            score += 1

                        # 再次检查槽位是否已满
                        if len(slots) >= SLOT_COLS:
                            game_over = True

                        # 检查胜利条件
                        if check_victory():
                            game_won = True
                            game_over = True

    # 更新下落卡片位置
    new_falling_cards = []
    for card, x, y, target_x, target_y in falling_cards:
        if y < target_y:
            y += FALLING_SPEED  # 使用速度变量更新卡片位置
            new_falling_cards.append((card, x, y, target_x, target_y))
        else:
            y = target_y
    falling_cards = new_falling_cards

    # 绘制界面
    if background_img:
        screen.blit(background_img, (0, 0))
    else:
        screen.fill(BG_COLOR)

    # 绘制卡片堆
    for row in range(GRID_ROWS):
        for col in range(GRID_COLS):
            x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
            y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
            stack = grid[row][col]
            for i, card_type in enumerate(stack):
                offset_x = i * (STACK_OFFSET // 2)  # 水平偏移
                offset_y = i * STACK_OFFSET  # 垂直偏移
                if card_images:
                    screen.blit(card_images[card_type], (x + offset_x, y - offset_y))
                else:
                    pygame.draw.rect(screen, COLORS[card_type],
                                     (x + offset_x, y - offset_y, CARD_WIDTH, CARD_HEIGHT))

    # 绘制下落中的卡片
    for card, x, y, _, _ in falling_cards:
        if card_images:
            screen.blit(card_images[card], (x, y))
        else:
            pygame.draw.rect(screen, COLORS[card], (x, y, CARD_WIDTH, CARD_HEIGHT))

    # 绘制槽位背景
    if slot_bg_img:
        screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
    else:
        pygame.draw.rect(screen, (200, 200, 200),
                         (SLOT_LEFT - 5, SLOT_TOP - 5,
                          slot_width + 10, SLOT_HEIGHT + 10),
                         border_radius=10)

    # 绘制槽位中的卡片
    for i, card in enumerate(slots):
        x = SLOT_LEFT + i * (CARD_WIDTH + 5)
        if card_images:
            screen.blit(card_images[card], (x, SLOT_TOP))
        else:
            pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))

    # 绘制道具按钮
    if button_image:
        screen.blit(button_image, (ITEM_BUTTON_LEFT, ITEM_BUTTON_TOP))

    # 显示按钮可用次数，修改显示格式
    font = pygame.font.Font(None, 36)
    text = font.render(f"x{ITEM_USE_TIMES}", True, (255, 0, 0) if ITEM_USED else (0, 0, 0))
    text_rect = text.get_rect(topleft=(ITEM_BUTTON_LEFT + ITEM_BUTTON_WIDTH + 5, ITEM_BUTTON_TOP))
    screen.blit(text, text_rect)

    # 绘制状态信息
    font = pygame.font.Font(None, 36)
    text = font.render(f"Score: {score}", True, (0, 0, 0))
    screen.blit(text, (20, 20))

    # 绘制槽位容量提示
    capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
    screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))

    if game_over:
        text = font.render("YOU WIN!" if game_won else "GAME OVER!",
                           True, (0, 255, 0) if game_won else (255, 0, 0))
        screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))

    pygame.display.flip()
    clock.tick(30)

pygame.quit()